package com.interview.rtc.aigc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.interview.rtc.aigc.dao.VerificationCodeDao;
import com.interview.rtc.aigc.mapper.VerificationCodeMapper;
import com.interview.rtc.aigc.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    private VerificationCodeMapper verificationCodeMapper;

     @Transactional
    public boolean sendVerificationCode(String phone) {
        // 先使该手机号之前的验证码失效
        invalidateCode(phone);

        //生成code
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000)); // 6位随机验证码
        // 创建新的验证码
        VerificationCodeDao verificationCode = new VerificationCodeDao();
        verificationCode.setPhone(phone);
        verificationCode.setCode(code);
        verificationCode.setExpireTime(new Date(System.currentTimeMillis() + 5 * 60 * 1000)); // 5分钟过期
        verificationCode.setIsUsed(0);

        verificationCodeMapper.insert(verificationCode);
        return true;
    }

    @Override
    @Transactional
    public boolean verifyCode(String phone, String code) {
        LambdaQueryWrapper<VerificationCodeDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VerificationCodeDao::getPhone, phone)
               .eq(VerificationCodeDao::getCode, code)
               .eq(VerificationCodeDao::getIsUsed, 0)
               .gt(VerificationCodeDao::getExpireTime, new Date());

        VerificationCodeDao verificationCode = verificationCodeMapper.selectOne(wrapper);
        if (verificationCode != null) {
            verificationCode.setIsUsed(1);
            verificationCodeMapper.updateById(verificationCode);
            return true;
        }
        return false;
    }


    public void invalidateCode(String phone) {
        LambdaQueryWrapper<VerificationCodeDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VerificationCodeDao::getPhone, phone)
               .eq(VerificationCodeDao::getIsUsed, 0);

        verificationCodeMapper.delete(wrapper);
    }
}
